package com.shimao.celnet.payment.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shimao.celnet.payment.config.ConstantConfig;
import com.shimao.celnet.payment.model.request.CallIn_OutPayUppaidAmoutRequest;
import com.shimao.celnet.payment.util.GetJFSystemToken;
import com.shimao.celnet.payment.util.MyDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;

/**外部系统----》支付系统
 * Created by glean on 2018/9/13.
 * 数据：房源应收账单（月度分类）获取
 数据范围：应收费用，挂起（审批不通过），银行托收（未出盘），应收费用调整（审批通过），违约金调整（审批通过）"
 */
@RestController
@RequestMapping(value = "/payment")
@Api("接口：外部系统 → 支付系统，数据：房源应收账单（月度分类）获取")
public class CallIn_outPayUppaidAmoutContrlloer {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private GetJFSystemToken getJFSystemToken;

    @Autowired
    private ConstantConfig constantConfig;
    @ApiOperation("外部获取未缴数据")
    @RequestMapping(value = "/uppaidamountout", method = RequestMethod.POST)
    public Object uppaidAmoutOutContrller(@RequestBody @Valid CallIn_OutPayUppaidAmoutRequest requestJson,BindingResult result) throws Exception{
        logger.info(String.valueOf(MyDateUtil.DateToStr(new Date(), MyDateUtil.formatDefaultTimestamp))+"===================外部获取未缴数据开始=======================");
        //解析请求参数
        CallIn_OutPayUppaidAmoutRequest requestUppaidAmout = requestJson;
        requestUppaidAmout.setPageNum("1");
        requestUppaidAmout.setPageSize("50");
        //获取token
        String token = getJFSystemToken.getJFSystemNewToken("","1005");
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        //请求方式
       //正式 HttpPost httpPost = new HttpPost("http://smsf.shimaowy.com:8888/api/fee/payment/uppaidamount_out");
        HttpPost httpPost = new HttpPost("https://smsf-test.shimaowy.com/api/fee/payment/uppaidamount_out");
        httpPost.addHeader("token",token);
        //请求收费系统
        // 设置请求的参数
        JSONObject object = new JSONObject();//实际请求body，这里给的空，所以报用户名不存在
        object.put("houseSFID",requestUppaidAmout.getHouseSFID());
        object.put("pageNum",requestUppaidAmout.getPageNum());
        object.put("pageSize",requestUppaidAmout.getPageSize());
        logger.info("请求信息："+object.toString());
        StringEntity entity = new StringEntity(object.toString(), "utf-8");
        //entity.setContentEncoding("UTF-8");
        //实例化之后还需要再次设置一下ContentType 不然会默认修改格式为 text/plain
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        JSONObject reqObject = new JSONObject();
        //执行请求
        CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
        //返回参数
        HttpEntity httpEntity = response.getEntity();
        reqObject = JSON.parseObject(EntityUtils.toString(httpEntity, "UTF-8"));
        System.out.println("***************************:"+reqObject.toString());
        logger.info("响应信息："+reqObject.toString());
        //记录数
        String count = null;
        //应缴的总金额数
        float totalAmout = 0;
        //数据封装
        JSONObject responseObject = new JSONObject();  //响应json
        //封装数据json
        JSONObject responsedata = new JSONObject();

        if ("0".equals(reqObject.getString("errcode"))){  //请求收费系统数据成功
            //封装成功code
            responseObject.put("errcode","0000");
            //获取请求中的data数据
            String data  = reqObject.getString("data");
            JSONObject dataObject = JSON.parseObject(data);
            //将房子的sfid放入响应数据data中
            responsedata.put("houseSFID",dataObject.getString("houseSFID"));
            if("0".equals(dataObject.getString("totalPage"))){
                //将应缴总金额放入响应数据data中
                responsedata.put("totalAmount","0");
                //将应缴的数量放入响应响应json
                responsedata.put("count","0");

            }else {
                //将data中的集合取出
                String paymentList = dataObject.getString("paymentList");
                JSONArray paymentArray = JSON.parseArray(paymentList);
                count = String.valueOf(paymentArray.size());
                //将data中的集合遍历计算总金额
                for (int i = 0; i<paymentArray.size();i++){
                    totalAmout += Float.valueOf(paymentArray.getJSONObject(i).getString("totalReceivableAmount"));
                }
                //将应缴总金额放入响应数据data中
                responsedata.put("totalAmount",String.valueOf(totalAmout));
                //将应缴的数量放入响应响应json
                responsedata.put("count",count);
            }

        }else {
            responseObject.put("errcode","1001");
            responseObject.put("data",responsedata);
            responseObject.put("errmsg","error");
        }
        //将data放入响应json
        responseObject.put("data",responsedata);
         //将响应信息放入响应json
         responseObject.put("errmsg","OK");
         System.out.println("==返回信息===:"+responseObject.toString()) ;
        logger.info("==返回信息:"+responseObject.toString());
        logger.info("===================外部获取未缴数据结束=======================");
        //返回数据
        return responseObject;
    }

}
